package db

import (
	"fmt"
	"github.com/sirupsen/logrus"
	"goadmin/config"
	l "goadmin/internal/logger"
	"gorm.io/driver/postgres"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"time"
)

// 初始化db
func Setup() {
	var dsn = fmt.Sprintf("user=%s password=%s dbname=%s port=%d sslmode=%s TimeZone=%s",
		config.DB_SETTING.User,
		config.DB_SETTING.Password,
		config.DB_SETTING.DbName,
		config.DB_SETTING.Port,
		config.DB_SETTING.SslMode,
		config.DB_SETTING.TimeZone)

	// logger
	newLogger := l.GormLogger{
		LogI:          l.LOG.WithFields(logrus.Fields{}),
		LogLevel:      logger.Info,
		SlowThreshold: 100 * time.Millisecond,
	}

	var err error
	DB, err = gorm.Open(postgres.Open(dsn), &gorm.Config{
		Logger: newLogger,
	})
	if err != nil {
		panic(err)
	}

	setConnectionPool()
	autoMigrate()
}

// 设置连接处
func setConnectionPool() {
	sqlDB, err := DB.DB()
	if err != nil {
		panic(err)
	}

	// SetMaxIdleConns 设置空闲连接池中连接的最大数量
	sqlDB.SetMaxIdleConns(10)

	// SetMaxOpenConns 设置打开数据库连接的最大数量。
	sqlDB.SetMaxOpenConns(100)

	// SetConnMaxLifetime 设置了连接可复用的最大时间。
	sqlDB.SetConnMaxLifetime(time.Hour)
}

// 维护表结构
func autoMigrate() {

}
